package com.ecp.commons.bean;

import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Page {

	private int				totalCount;
	private int				pageSize	= 99999;
	private int				pageCount;
	private int				currentPage	= 1;
	private int				start;
	private List<String>	pageList;

	public Page() {
		new Page(pageSize);
	}

	public Page(int pageSize) {
		this.pageSize = pageSize;
	}

	public JSONObject toJSON() {
		JSONObject jobj = new JSONObject();
		try {
			jobj.put("totalCount", this.totalCount);
			jobj.put("pageSize", this.pageSize);
			jobj.put("pageCount", this.getPageCount());
			jobj.put("currentPage", this.currentPage);
			jobj.put("isFirst", this.isFirst());
			jobj.put("isLast", this.isLast());

			JSONArray jary = new JSONArray();
			JSONObject jPage = null;
			for (String s : this.getPageList()) {
				jPage = new JSONObject();
				jPage.put("name", s);
				jary.put(jPage);
			}
			jobj.put("pageList", jary);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jobj;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageCount() {
		pageCount = totalCount / pageSize;
		if (totalCount % pageSize != 0) {
			pageCount++;
		}
		return pageCount;
	}

	public int getStart() {
		start = (this.currentPage - 1) * this.pageSize;
		return start;
	}
	
	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public void setStartLimit(int start, int limit) {
		this.pageSize = limit;
		this.currentPage = start / limit + 1;
	}


	public boolean isFirst() {
		return currentPage == 1 ? true : false;
	}

	public boolean isLast() {
		return currentPage == getPageCount() ? true : false;
	}

	public List<String> getPageList() {
		pageList = new LinkedList<String>();
		int n = 5 * ((currentPage - 1) / 5) + 1;
		for (int i = n; i <= n + 5; i++) {
			if (i > pageCount) {
				break;
			}
			pageList.add(String.valueOf(i));
		}
		return pageList;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}
}